#!/bin/bash

# DevOps管理平台启动脚本

echo "🚀 启动DevOps管理平台..."

# 检查服务状态
check_service() {
    local service=$1
    local port=$2
    
    if lsof -Pi :$port -sTCP:LISTEN -t >/dev/null ; then
        echo "✅ $service 正在运行 (端口 $port)"
        return 0
    else
        echo "❌ $service 未运行 (端口 $port)"
        return 1
    fi
}

# 启动MySQL
echo "📊 检查MySQL服务..."
if ! check_service "MySQL" 3306; then
    echo "启动MySQL服务..."
    sudo systemctl start mysql
    sleep 2
fi

# 启动Redis
echo "🔴 检查Redis服务..."
if ! check_service "Redis" 6379; then
    echo "启动Redis服务..."
    sudo systemctl start redis-server
    sleep 2
fi

# 启动Django后端 (ASGI服务器，支持WebSocket)
echo "🐍 启动Django ASGI服务器 (支持WebSocket)..."
cd devops-backend
if ! check_service "Django" 8000; then
    echo "启动Django ASGI服务器..."
    source venv/bin/activate
    # 检查是否安装了daphne
    python -c "import daphne" 2>/dev/null
    if [ $? -ne 0 ]; then
        echo "安装daphne..."
        pip install daphne
    fi
    nohup daphne -b 0.0.0.0 -p 8000 devops_platform.asgi:application > ../logs/django.log 2>&1 &
    sleep 3
fi

# 启动Celery Worker
echo "⚡ 启动Celery Worker..."
if ! pgrep -f "celery.*worker" > /dev/null; then
    echo "启动Celery Worker..."
    source venv/bin/activate
    nohup celery -A devops_platform worker --loglevel=info > ../logs/celery_worker.log 2>&1 &
    sleep 2
fi

# 启动Celery Beat (定时任务调度器)
echo "⏰ 启动Celery Beat..."
if ! pgrep -f "celery.*beat" > /dev/null; then
    echo "启动Celery Beat..."
    source venv/bin/activate
    nohup celery -A devops_platform beat --loglevel=info > ../logs/celery_beat.log 2>&1 &
    sleep 2
fi

cd ..

# 启动Vue前端
echo "🎨 启动Vue前端服务..."
cd devops-frontend
if ! check_service "Vue.js" 8080; then
    echo "启动Vue开发服务器..."
    nohup npm run dev > ../logs/vue.log 2>&1 &
    sleep 3
fi

cd ..

# 创建日志目录
mkdir -p logs

echo ""
echo "🎉 DevOps管理平台启动完成！"
echo ""
echo "📋 服务状态："
check_service "MySQL" 3306
check_service "Redis" 6379
check_service "Django" 8000
check_service "Vue.js" 8080

echo ""
echo "🌐 访问地址："
echo "   前端应用: http://localhost:8082 或 http://10.0.0.201:8082"
echo "   后端API: http://localhost:8000/api (支持WebSocket)"
echo "   Django管理: http://localhost:8000/admin"
echo ""
echo "👤 默认登录信息："
echo "   用户名: admin"
echo "   密码: admin123"
echo ""
echo "📝 日志文件："
echo "   Django ASGI: logs/django.log"
echo "   Celery Worker: logs/celery_worker.log"
echo "   Celery Beat: logs/celery_beat.log"
echo "   Vue.js: logs/vue.log"
echo ""
echo "🛑 停止服务请运行: ./stop.sh"
